//
//  MoreCustomerViewController.m
//  QRMaster
//
//  Created by liuyunlong on 15/10/28.
//  Copyright © 2015年 myApple. All rights reserved.
//

#import "MoreCustomerViewController.h"

#import "RequestNetWork.h"
#import "PromptInfoView.h"
#import "Reachability.h"
#import "UIImageView+WebCache.h"
#import "MoreCustomerViewController.h"
#import "MJRefresh.h"
#import "GuestManagerViewController.h"
#import "groupInfoViewController.h"
#import "customSearchModel.h"
#import "customSearchTableViewCell.h"
@interface MoreCustomerViewController ()
{
    NSString *customerStatusStr;
    NSString *searchKeyStr;
    
    UIView *titleView;
    
    UITableView *searchResultTableView;
    
    NSMutableArray *searchArray;
    
    NSMutableArray *dataArray;
    NSMutableDictionary *dataDic;
    
    UIActivityIndicatorView * _activityIndicator;
    
    int pageIndex;
    
    NSString *communityIdStr;
    
    NSString *groupIdStr;             //组id
    NSString *clientIdStr;            //
    NSString *memberIdsStr;           //
}
@end

@implementation MoreCustomerViewController

-(id)initWIthCustomerStatus:(NSString *)customerStatus searchKey:(NSString *)searchKey communityId:(NSString *)communityId
{
    if (self==[super init])
    {
        customerStatusStr=customerStatus;
        searchKeyStr=searchKey;
        communityIdStr=communityId;
        self.title=searchKeyStr;
        pageIndex=1;
    }
    return self;
    
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor=[UIColor whiteColor];
    searchArray=[[NSMutableArray alloc]init];
    dataArray=[[NSMutableArray alloc]init];
    dataDic=[[NSMutableDictionary alloc]init];
    
    searchResultTableView=[[UITableView alloc]initWithFrame:CGRectMake(0, 0, UI_SCREEN_WIDTH, UI_SCREEN_HEIGHT-64) style:UITableViewStylePlain];
    searchResultTableView.backgroundColor = UIColorFromRGB(0xebebeb);
    searchResultTableView.delegate=self;
    searchResultTableView.dataSource=self;
    [self.view addSubview:searchResultTableView];
    [self setExtraCellLineHidden:searchResultTableView];
    
    UIView * headerView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, UI_SCREEN_WIDTH, 16)];
    headerView.backgroundColor = UIColorFromRGB(0xebebeb);
    UIView * lineView = [[UIView alloc] initWithFrame:CGRectMake(0, 15.5, UI_SCREEN_WIDTH, 0.5)];
    lineView.backgroundColor = RGBA(193, 193, 193, 1);
    [headerView addSubview:lineView];
    searchResultTableView.tableHeaderView = headerView;
    
    UIView * footerView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, UI_SCREEN_WIDTH, 0.5)];
    lineView.backgroundColor = RGBA(193, 193, 193, 1);
    searchResultTableView.tableFooterView = footerView;
    
    __weak MoreCustomerViewController * weakSelf = self;
    [searchResultTableView.mj_header beginRefreshing];
    searchResultTableView.mj_footer = [MJRefreshAutoFooter footerWithRefreshingBlock:^{
        pageIndex = 1;
//        [weakSelf getCustomerInfo:communityIdStr search:searchKeyStr currentPage:[NSString stringWithFormat:@"%i",pageIndex] size:@"10" status:customerStatusStr];
    }];

    [searchResultTableView.mj_header beginRefreshing];
    searchResultTableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        
        if ([[dataDic objectForKey:@"totalcustomer"] intValue]<=dataArray.count)
        {
            [PromptInfoView showMessage:NSLocalizedString(@"noMoreShareInfo", nil)];
           
        }
        else
        {
            pageIndex ++;
            [self getCustomerInfo:communityIdStr search:searchKeyStr currentPage:[NSString stringWithFormat:@"%i",pageIndex] size:@"10" status:customerStatusStr];
        }

    }];

    [self getCustomerInfo:communityIdStr search:searchKeyStr currentPage:[NSString stringWithFormat:@"%i",pageIndex] size:@"10" status:customerStatusStr];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return dataArray.count;
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 56;
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    NSString * cellId = @"cell";
    customSearchTableViewCell * cell = [tableView dequeueReusableCellWithIdentifier:cellId];
    if (!cell) {
        cell = [[customSearchTableViewCell alloc]init];
    }
    cell.backgroundColor = [UIColor whiteColor];
    cell.customHeadImg = [[dataArray objectAtIndex:indexPath.row] objectForKey:@"headurl"];
    cell.customName = [[dataArray objectAtIndex:indexPath.row] objectForKey:@"name"];
    NSString * areaCode = [[dataArray objectAtIndex:indexPath.row] objectForKey:@"areaCode"];
    if ([areaCode isEqualToString:[QRSingleton sharedQRSingleton].currentAreaCodeString]) {
        cell.customMobile = [[dataArray objectAtIndex:indexPath.row] objectForKey:@"mobile"];
    }
    else
    {
        cell.customMobile = [NSString stringWithFormat:@"+%@ %@",areaCode,[[dataArray objectAtIndex:indexPath.row] objectForKey:@"mobile"]];
    }
    return cell;
    
}



- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    if([@"0" isEqualToString:customerStatusStr]==YES)
    {
        GuestManagerViewController * gmvc = [[GuestManagerViewController alloc]init];
        GuestModel *model=[[GuestModel alloc]init];
        model.guestName=[[dataArray objectAtIndex:indexPath.row] objectForKey:@"name"];
        model.telePhone=[NSString stringWithFormat:@"%@",[[dataArray objectAtIndex:indexPath.row] objectForKey:@"mobile"]];
        model.email=[[dataArray objectAtIndex:indexPath.row] objectForKey:@"email"];
        model.guestid=[[dataArray objectAtIndex:indexPath.row] objectForKey:@"id"];
        model.headUrl=[[dataArray objectAtIndex:indexPath.row] objectForKey:@"headurl"];
        model.sex=[[dataArray objectAtIndex:indexPath.row] objectForKey:@"gender"];
        model.certificaties=[[dataArray objectAtIndex:indexPath.row] objectForKey:@"identity"];
        model.firstChar=[[dataArray objectAtIndex:indexPath.row] objectForKey:@"firstchar"];
        model.areaCode = [[dataArray objectAtIndex:indexPath.row] objectForKey:@"areaCode"];
        [QRSingleton sharedQRSingleton].guestPushIndex = 2;
        gmvc.model = model;
        gmvc.communityid = communityIdStr;
        gmvc.comeFrom = NO;
        [self.navigationController pushViewController:gmvc animated:YES];
    }
    else
    {
        GuestModel * gModel = [[GuestModel alloc]init];
        gModel.guestName = [[dataArray objectAtIndex:indexPath.row]  objectForKey:@"name"];
        gModel.sex = [[dataArray objectAtIndex:indexPath.row]  objectForKey:@"gender"];
        gModel.email = [[dataArray objectAtIndex:indexPath.row]  objectForKey:@"email"];;
        gModel.telePhone = [[dataArray objectAtIndex:indexPath.row]  objectForKey:@"mobile"];
        gModel.isGroupManager = @"1";
        gModel.certificaties = [[dataArray objectAtIndex:indexPath.row]  objectForKey:@"identity"];
        gModel.areaCode = [[dataArray objectAtIndex:indexPath.row] objectForKey:@"areaCode"];
        groupInfoViewController * gifv = [[groupInfoViewController alloc]init];
        gifv.groupId = [[dataArray objectAtIndex:indexPath.row]  objectForKey:@"id"];
        gifv.groupName = [[dataArray objectAtIndex:indexPath.row]  objectForKey:@"groupname"];
        
        gifv.model = gModel;
        [self.navigationController pushViewController:gifv animated:YES];
    }
}

//删除多余表格
-(void)setExtraCellLineHidden: (UITableView *)tableView
{
    UIView *view = [UIView new];
    view.backgroundColor = [UIColor clearColor];
    [tableView setTableFooterView:view];
    
}

-(void)getCustomerInfo:(NSString *)communityId search:(NSString *)search currentPage:(NSString *)currentPage size:(NSString *)size status:(NSString *)status
{
    if ([self IsHaveNetwork]) {
        
        return;
    }
    if(search==nil || [@"" isEqualToString:search]==YES)
    {
        [PromptInfoView showMessage:NSLocalizedString(@"SearchError", nil)];
        return;
    }
    [_activityIndicator startAnimating];
    NSUserDefaults * userInfo = [NSUserDefaults standardUserDefaults];
    NSMutableDictionary * postDict = [[NSMutableDictionary alloc]init];
    [postDict setValue:[userInfo objectForKey:@"uid"] forKey:@"id"];
    [postDict setValue:[userInfo objectForKey:@"token"] forKey:@"token"];
    [postDict setValue:communityId forKey:@"communityId"];
    [postDict setValue:search forKey:@"search"];
    [postDict setValue:currentPage forKey:@"currentPage"];
    [postDict setValue:size forKey:@"size"];
    [postDict setValue:status forKey:@"status"];
    RequestNetWork * rnw = [[RequestNetWork alloc]init];
    [rnw initWithPath:POST(SEARCHCUSTOMER) params:postDict block:^(id downLoadData, id error)
    {
        [searchResultTableView.mj_header endRefreshing];
        [searchResultTableView.mj_footer endRefreshing];
        
        if ([downLoadData objectForKey:@"data"] != nil) {
            if ([@"0" isEqualToString:customerStatusStr]==YES) {
                dataDic = [[[downLoadData objectForKey:@"data"] objectForKey:@"normal"]objectForKey:@"page"];
                pageIndex=[[[[downLoadData objectForKey:@"data"] objectForKey:@"normal"] objectForKey:@"currentpage"]intValue];
                if (1==pageIndex) {
                    dataArray = [[[downLoadData objectForKey:@"data"] objectForKey:@"normal"] objectForKey:@"customers"];
                }
                else
                {
                    [dataArray addObjectsFromArray:[[[downLoadData objectForKey:@"data"] objectForKey:@"normal"] objectForKey:@"customers"]];
                }
                
                for(int i = 0; i<dataArray.count; i++)
                {
                    [((NSMutableDictionary *)[dataArray objectAtIndex:i]) setObject:[self FirstCharToStr:[[dataArray objectAtIndex:i] objectForKey:@"firstchar"]] forKeyedSubscript:@"firstchar"];
                }
                
                //首字母处理
                for(int i = 0; i<dataArray.count; i++)
                {
                    for(int j = i; j<dataArray.count; j++)
                    {
                        if([[[dataArray objectAtIndex:i] objectForKey:@"firstchar"] isEqualToString:[[dataArray objectAtIndex:j] objectForKey:@"firstchar"]]==YES &&j!=i)
                        {
                            [((NSMutableDictionary *)[dataArray objectAtIndex:j]) setObject:@"" forKeyedSubscript:@"firstchar"];
                        }
                    }
                }
                
            }
            else
            {
                //                dataArray = [[data objectForKey:@"group"] objectForKey:@"customers"];
                dataDic = [[[downLoadData objectForKey:@"data"] objectForKey:@"group"]objectForKey:@"page"];
                pageIndex=[[[[downLoadData objectForKey:@"data"] objectForKey:@"group"] objectForKey:@"currentpage"]intValue];
                
                if (1==pageIndex) {
                    dataArray = [[[downLoadData objectForKey:@"data"] objectForKey:@"group"] objectForKey:@"customers"];
                }
                else
                {
                    [dataArray addObjectsFromArray:[[[downLoadData objectForKey:@"data"] objectForKey:@"group"] objectForKey:@"customers"]];
                }
                
                //首字母处理
                for(int i = 0; i<dataArray.count; i++)
                {
                    for(int j = i; j<dataArray.count; j++)
                    {
                        if([[[dataArray objectAtIndex:i] objectForKey:@"firstchar"] isEqualToString:[[dataArray objectAtIndex:j] objectForKey:@"firstchar"]]==YES &&j!=i)
                        {
                            [[dataArray objectAtIndex:j] setObject:@"" forKeyedSubscript:@"firstchar"];
                        }
                    }
                }
            }
        }
        else
        {
            [PromptInfoView showMessage:[error objectForKey:@"info"]];
        }
        [searchResultTableView reloadData];
        [_activityIndicator stopAnimating];
    }];
}

- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (editingStyle == UITableViewCellEditingStyleDelete) {
        if ([@"0" isEqualToString:customerStatusStr]==YES) {
            memberIdsStr=[[dataArray objectAtIndex:indexPath.row] objectForKey:@"id"];
            [self delete:@"0"];
 
        }
        else if ([@"1" isEqualToString:customerStatusStr]==YES) {
            groupIdStr=[[dataArray objectAtIndex:indexPath.row] objectForKey:@"groupId"];
            clientIdStr=[[dataArray objectAtIndex:indexPath.row] objectForKey:@"id"];
            [self delete:@"1"];
            
        }
    }
    else if (editingStyle == UITableViewCellEditingStyleInsert) {
        // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
    }
}
-(UITableViewCellEditingStyle)tableView:(UITableView *)tableView editingStyleForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return UITableViewCellEditingStyleDelete;
}
-(NSString *)tableView:(UITableView *)tableView titleForDeleteConfirmationButtonForRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    return  NSLocalizedString(@"deleteCell", nil);
}

-(BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath
{
    return YES;
}
- (BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath {
    return YES;
}
- (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)fromIndexPath toIndexPath:(NSIndexPath *)toIndexPath {
    
    
}

-(void)delete:(NSString *)type//0表示普通，1表示组
{
    if ([@"0" isEqualToString:type]==YES) {
        [self deleteCustomers:communityIdStr memberIds:memberIdsStr];
    }
    else if ([@"1" isEqualToString:type]==YES)
    {
        [self deleteGroup:communityIdStr groupId:groupIdStr clientId:clientIdStr];
    }
}

//删除普通客户
-(void)deleteCustomers:(NSString *)communityId memberIds:(NSString *)memberIds
{
    if ([self IsHaveNetwork]) {
        return;
    }
    [_activityIndicator startAnimating];
    NSUserDefaults * userInfo = [NSUserDefaults standardUserDefaults];
    NSMutableDictionary * postDict = [[NSMutableDictionary alloc]init];
    [postDict setValue:[userInfo objectForKey:@"uid"] forKey:@"id"];
    [postDict setValue:[userInfo objectForKey:@"token"] forKey:@"token"];
    [postDict setValue:communityId forKey:@"communityId"];
    [postDict setValue:memberIds forKey:@"memberIds"];
    RequestNetWork * rnw = [[RequestNetWork alloc]init];
    [rnw initWithPath:POST(DELETECUSTOMERS) params:postDict block:^(id downLoadData, id error)
    {
        if ([downLoadData objectForKey:@"data"]!=nil) {
            pageIndex=1;
            [self getCustomerInfo:communityIdStr search:searchKeyStr currentPage:[NSString stringWithFormat:@"%i",pageIndex] size:@"10" status:customerStatusStr];
        }
        else
        {
            [PromptInfoView showMessage:[error objectForKey:@"info"]];
        }
        [_activityIndicator stopAnimating];
    }];
}

//删除组客户
-(void)deleteGroup:(NSString *)communityId groupId:(NSString *)groupId clientId:(NSString *)clientId
{
    if ([self IsHaveNetwork]) {
        return;
    }
    [self startWaiting:nil color:nil addToView:self.view];
    NSUserDefaults * userInfo = [NSUserDefaults standardUserDefaults];
    NSMutableDictionary * postDict = [[NSMutableDictionary alloc]init];
    [postDict setValue:[userInfo objectForKey:@"uid"] forKey:@"id"];
    [postDict setValue:[userInfo objectForKey:@"token"] forKey:@"token"];
    [postDict setValue:communityId forKey:@"communityId"];
    [postDict setValue:groupId forKey:@"groupId"];
    [postDict setValue:clientId forKey:@"clientId"];
    RequestNetWork * rnw = [[RequestNetWork alloc]init];
    [rnw initWithPath:POST(DELETEGROUPCUSTOMER) params:postDict block:^(id downLoadData, id error)
    {
        if ([downLoadData objectForKey:@"data"] != nil) {
            pageIndex=1;
            [self getCustomerInfo:communityIdStr search:searchKeyStr currentPage:[NSString stringWithFormat:@"%i",pageIndex] size:@"10" status:customerStatusStr];
        }
        else
        {
            [PromptInfoView showMessage:[error objectForKey:@"info"]];
        }
        [self stopWaiting];
    }];
}


@end
